package com.seeyon.apps.cfca.controller;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.cfca.manager.SealPdfMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.util.Date;
import java.util.HashMap;

@Slf4j
@RestController
public class SignatureController {
    @Autowired
    private SealPdfMessage sealPdfMessage;

    @PostMapping("/signature")
    public JSONObject addUser(@RequestBody JSONObject restJson) {
        InputStream inputStream = null;
        JSONObject result = new JSONObject();
        try {
            log.info("入参restJson:" + restJson.toString());
            JSONObject json = restJson.getJSONObject("storageKey");
            JSONObject edition = json.getJSONObject("edition");
            String content = edition.getString("content");
            String functionName = new Date().getTime() + "SealPdfMessageImpl";

            //获取需签章的文件
            JSONObject jsonObject = sealPdfMessage.fileDownload(content);
            if (jsonObject.get("msg") != null){
                return jsonObject;
            }

            byte[] pdfByte = (byte[]) jsonObject.get("pdfByte");
            result = sealPdfMessage.doWork(functionName, "OA", pdfByte);
            if (result != null && result.get("storageKey") != null){
                edition.put("content" , result.getString("storageKey"));
                json.put("edition" , edition);
                restJson.put("storageKey" , JSONObject.toJSONString(json));
            }else {
                return result;
            }
        }catch (Exception e){
            log.error("调用签章接口报错：",e);
            result.put("msg" , e);
            return result;
        } finally {
            try {
                if (inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("Pdf流关闭报错：",e);
            }
        }
        log.info("出参restJson:" + JSONObject.toJSONString(restJson));
        return restJson;
    }

}
